package com.pp.wsi;


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

/**
 * Handles requests for the application home page.
 */

@SessionAttributes
@Controller
public class HomeController {
	
	private Users users;
	
	List<Form1> forms1;
	List<Form2> forms2;
	List<Form3> forms3;
	
	public HomeController() {		
		users = new Users();
		
		forms1 =new LinkedList<Form1>();	
		forms2 =new LinkedList<Form2>();	
		forms3 =new LinkedList<Form3>();	
	}
	
	public Form1 getForm1(String username){
		for(Form1 tmp:forms1){
			if (tmp.getUsername().equals(username)) 
				return tmp;
		}		
		return null;
	}
	
	
	public Form2 getForm2(String username){
		for(Form2 tmp:forms2){
			if (tmp.getUsername().equals(username)) 
				return tmp;
		}		
		return null;
	}
	
	
	public Form3 getForm3(String username){
		for(Form3 tmp:forms3){
			if (tmp.getUsername().equals(username)) 
				return tmp;
		}
		return null;
	}
	
	public void addForm1(String username,Form1 newForm1){
		
		if ( getForm1(username) == null) {
			forms1.add(newForm1);	
		}
		else {
			getForm1(username).setAge(newForm1.getAge());
			getForm1(username).setBirthday(newForm1.getBirthday());
			getForm1(username).setEmail(newForm1.getEmail());
			getForm1(username).setEyecolor(newForm1.getEyecolor());
			getForm1(username).setLastname(newForm1.getLastname());
			getForm1(username).setName(newForm1.getName());
			getForm1(username).setPhone(newForm1.getUrl());
			getForm1(username).setUrl(newForm1.getUrl());			
			getForm1(username).setWeight(newForm1.getWeight());			
		}			
	}
	
	public void addForm2(String username,Form2 newForm2){		
		if ( getForm2(username) == null) {
			forms2.add(newForm2);	
		}
		else {
			getForm2(username).setCity(newForm2.getCity());
			getForm2(username).setCountry(newForm2.getCountry());
		}			
	}
	
	public void addForm3(String username,Form3 newForm3){	
		if ( getForm3(username) == null) {
			forms3.add(newForm3);	
		}
		else {
			getForm3(username).setFather(newForm3.getFather());
			getForm3(username).setMother(newForm3.getMother());			
		}	
	}
	
	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
	
	
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String home(Locale locale, Model model) {
		logger.info("Welcome home! The client locale is {}.", locale);
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		logger.debug("test");
		
		return "home";
	}
	
	@RequestMapping(value = "/tutorial", method = RequestMethod.GET)
	public String tutorial(Locale locale, Model model) {
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		logger.debug("test");
		
		return "tutorial";
	}
	
	
	@RequestMapping(value = "/toomany", method = RequestMethod.GET)
	public String tooManySessions(Locale locale, Model model) {
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate );
		
		logger.debug("test");
		
		return "toomany";
	}
	
	@RequestMapping(value = "/admin/forms", method = RequestMethod.GET)
	public String forms(Locale locale, Model model) {
		
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		String username = authentication.getName();	
		
		return "admin/forms";
	}
	
	
	@RequestMapping(value = "/admin/form1", method = RequestMethod.GET)
	public String form1(Locale locale, Model model) {		
		
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		String username = authentication.getName();
		
		User tmp = users.getUser(username);
		if (tmp!=null && getForm1(username)!=null){	
			if ( getForm1(username).getLastname() != null)
				model.addAttribute("name", getForm1(username).getName());
			if ( getForm1(username).getLastname() != null)
				model.addAttribute("lastname", getForm1(username).getLastname());	
			if ( getForm1(username).getAge() != null)
				model.addAttribute("age", getForm1(username).getAge());	
			if (  getForm1(username).getWeight() != null)
				model.addAttribute("weight", getForm1(username).getWeight());	
			if (  getForm1(username).getEyecolor() != null)
				model.addAttribute("eyecolor", getForm1(username).getEyecolor());	
			if (  getForm1(username).getBirthday() != null)
				model.addAttribute("birthday", getForm1(username).getBirthday());	
			if (  getForm1(username).getPhone() != null)
				model.addAttribute("phone", getForm1(username).getPhone());	
			if (  getForm1(username).getEmail() != null)
				model.addAttribute("email", getForm1(username).getEmail());	
			if (  getForm1(username).getUrl() != null)
				model.addAttribute("url", getForm1(username).getUrl());				
			
			return "admin/form1";	
		}else {
			User newUser = new User();
			newUser.setUsername(username);
			users.addUser(newUser);
			logger.info("Adding new user : " + username);
			return "admin/form1";
		}
			
		

		
	}
	
	@RequestMapping(value = "/admin/form2", method = RequestMethod.POST)
	public String form2(Locale locale, Model model) {		
		
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		String username = authentication.getName();
		
		if (getForm2(username) != null) {		
			if (!getForm2(username).getCountry().equals("")) {
	    		model.addAttribute("country", getForm2(username).getCountry());
	    	}
			
			if (!getForm2(username).getCity().equals("")) {
	    		model.addAttribute("city", getForm2(username).getCity());
	    	}
		}
		
		return "admin/form2";
	}
	
	@RequestMapping(value = "/admin/form3", method = RequestMethod.POST)
	public String form3(@ModelAttribute("form2") Form2 form2, BindingResult result, Model model) {		
		
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		String username = authentication.getName();
		
		if (result.hasErrors()) {
			logger.info("error");
			model.addAttribute("user", "Blad");			
			return "admin/form2";
			
	    }else {	
	    	
	    	form2.setUsername(username);
	    	addForm2(username,form2);	   
	    	
	    	logger.info("City " + form2.getCity() + " Country " + form2.getCountry());
	    	
	    	if (getForm3(username) != null) {	
		    	if (!getForm3(username).getMother().equals("")) {
		    		model.addAttribute("mother", getForm3(username).getMother());
		    	}
		    	
		    	if (!getForm3(username).getFather().equals("")) {
		    		model.addAttribute("father", getForm3(username).getFather());
		    	}
	    	}else {
	    		model.addAttribute("mother", null);
	    		model.addAttribute("father", null);
	    	}
	    	
	    	return "admin/form3";
	    }	
	}
	
	
	@RequestMapping(value = "/admin/summary1", method = RequestMethod.POST)
	public String summary1(@ModelAttribute("form1") Form1 form1, BindingResult result, Model model) {		
		
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		String username = authentication.getName();
		
		if (result.hasErrors()) {
			logger.info("error");
			model.addAttribute("user", "Blad");			
			return "admin/form1";
			
	    }else {	 
	    	
	    	form1.setUsername(username);	    	
	    	addForm1(username,form1);	
	    	logger.info(forms1.toString());
	    	
			model.addAttribute("name", getForm1(username).getName());
			model.addAttribute("lastname", getForm1(username).getLastname());				
			model.addAttribute("age", getForm1(username).getAge());	
			model.addAttribute("weight", getForm1(username).getWeight());	
			model.addAttribute("eyecolor", getForm1(username).getEyecolor());	
			model.addAttribute("birthday", getForm1(username).getBirthday());	
			model.addAttribute("phone", getForm1(username).getPhone());	
			model.addAttribute("email", getForm1(username).getEmail());	
			model.addAttribute("url", getForm1(username).getUrl());			
			
	    	return "admin/summary1";
	    	
	    }
		
	}
	
	@RequestMapping(value = "/admin/summary2", method = RequestMethod.POST)
	public String summary2(@ModelAttribute("form3") Form3 form3, BindingResult result, Model model) {	
		
		
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		String username = authentication.getName();
		
		if (result.hasErrors()) {
			logger.info("error");
			model.addAttribute("user", "Blad");			
			return "admin/form3";
			
	    }else {
	    	
	    	form3.setUsername(username);
	    	addForm3(username,form3) ;	
	    	
	    	logger.info("Mother " + form3.getMother() + " Father " + form3.getFather());
			
					
			model.addAttribute("name", getForm1(username).getName());
			model.addAttribute("lastname", getForm1(username).getName());			
			model.addAttribute("age", getForm1(username).getAge());	
			model.addAttribute("weight", getForm1(username).getWeight());	
			model.addAttribute("eyecolor", getForm1(username).getEyecolor());	
			model.addAttribute("birthday", getForm1(username).getBirthday());	
			model.addAttribute("phone", getForm1(username).getPhone());	
			model.addAttribute("email", getForm1(username).getEmail());	
			model.addAttribute("url", getForm1(username).getUrl());		
			
			logger.info("City " + getForm2(username).getCity() + " Country " + getForm2(username).getCountry());
			
			
			model.addAttribute("country", getForm2(username).getCountry());
			model.addAttribute("city", getForm2(username).getCity());
			
			logger.info("Mother " + getForm3(username).getMother() + " Father " + getForm3(username).getFather());
			
			model.addAttribute("mother", getForm3(username).getMother());
			model.addAttribute("father", getForm3(username).getFather());

	    	return "admin/summary2";
	    }	
	}
	 
	
	@RequestMapping(value="/login", method = RequestMethod.GET)
	public String login(ModelMap model ,  @RequestParam(value="success",required=false) String success) {	
		
		if (success != null) {
			if (success.contains("true")){			
				model.addAttribute("success", "true");
				model.addAttribute("result", "Poprawnie wylogowano użytkownika");	
			}	
		}
		
		return "admin/login";
	}
	
	@RequestMapping(value="/loginfailed", method = RequestMethod.GET)
	public String loginerror(ModelMap model ,  @RequestParam(value="result",required=false) String result) {
 
		model.addAttribute("error", "true");
		
		if (result != null) {
			if (result.equals("sessionExpired")){
				model.addAttribute("result", "Sesja wygas�a");
			}
			else if ( result.equals("sessionExpiredDuplicateLogin")){
				model.addAttribute("result", "Ktos zalogowal sie na Twoje konto w innej przegladarce");
			}
			else if ( result.equals("alreadyLogin")) {
				model.addAttribute("result", "Jestes juz zalogowany");
			}
			else if ( result.equals("errorAuthentication")) {
				model.addAttribute("result", "Zly  login lub haslo");
			}
			else {
				model.addAttribute("result", "Nie znany blad");				
			}
		}

		return "admin/login";
 
	}
 
	@RequestMapping(value="/logout", method = RequestMethod.GET)
	public String logout(ModelMap model) {
		return "admin/login?success=true";
	}
	
	@ResponseBody
	@RequestMapping(value="/country", method = RequestMethod.GET)
	public String country(ModelMap model) {		
		CountryCity cc = new CountryCity();	
		
		String output = "";
		Object[] countries = cc.getCountries().toArray();
		for(int i=0; i< cc.getCountries().size();i++ ){
			if (i==cc.getCountries().size()-1){
				output=output+((String)countries[i]);
			}else
				output=output+((String)countries[i])+",";
		}
	        
		logger.info(output);
		
		
		return output;
		
		
	}
	
	@ResponseBody
	@RequestMapping(value="/city", method = RequestMethod.GET)
	public String city(ModelMap model ,  @RequestParam(value="country",required=true) String country) {
		CountryCity cc = new CountryCity();

		String output = "";
		Object[] countries = cc.getCities(country).toArray();
		for(int i=0; i< cc.getCities(country).size();i++ ){
			if (i==cc.getCities(country).size()-1){
				output=output+((String)countries[i]);
			}else
				output=output+((String)countries[i])+",";
		}
	        
		logger.info(output);
		
		
		return output;
		
		
		
	}
	
	@RequestMapping(value="/admin/save", method = RequestMethod.GET)
	public String save(ModelMap model) {
		
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		String username = authentication.getName();		
		SaveForms(username);				
		
		return "admin/forms";
	}
	
	@RequestMapping(value="/show", method = RequestMethod.GET)
	public @ResponseBody Users showFroms(javax.servlet.http.HttpServletResponse r) {
		
		//Parser p=new Parser();
		Users tmpUsers = users;
		return users;
		//p.addUsers(tmpUsers);
		//p.parseAndRespond(r);
		
		
	}
	
	public void SaveForms(String username) {
		
		File dir = new File("../webapps/WSI/Forms");
		dir.mkdir();
		
		
		File file = new File(dir.getAbsoluteFile() + "/" +username + ".txt");		 
		
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {				
				e.printStackTrace();
			}
		}

		FileWriter fw = null;
		try {
			fw = new FileWriter(file.getAbsoluteFile());
		} catch (IOException e) {			
			e.printStackTrace();
		}
		
		BufferedWriter bw = new BufferedWriter(fw);
		
		try {
			
			bw.write("Imie: "  + 		getForm1(username).getName()+ "\n");
			bw.write("Naziwsko: "  + 	getForm1(username).getLastname()+ "\n");
			bw.write("Wiek: "  + getForm1(username).getAge()+ "\n");
			bw.write("Data urodzin: "  + getForm1(username).getBirthday()+ "\n");
			bw.write("Waga: "  + getForm1(username).getWeight()+ "\n");
			
			bw.write("Email: "  + getForm1(username).getEmail()+ "\n");
			bw.write("Numer telefonu: "  + getForm1(username).getPhone()+ "\n");
			bw.write("Strna internetowa: "  + getForm1(username).getUrl()+ "\n");
			
			bw.write("Panstwo: "  + getForm2(username).getCountry()+ "\n");
			bw.write("Miasto: "  + getForm2(username).getCity()+ "\n");
			
			bw.write("Imie Matki: "  + getForm3(username).getMother()+ "\n");
			bw.write("Imie Ojca: "  + getForm3(username).getFather()+ "\n");	
			
			Date date = new Date();
			DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG);
			
			users.getUser(username).setFinishDate(dateFormat.format(date));
			users.getUser(username).setFinished(true);
	
		} catch (IOException e) {			
			e.printStackTrace();
		}
		
		try {
			bw.close();
		} catch (IOException e) {			
			e.printStackTrace();
		}		
	}
	

	
}




